package com.demo.monitor_file_change;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;

/**
 * 启动后， 每5秒扫描指定路径下文件的变化，很方便
 * @author shenguangyang
 */
public class ApacheFileMonitor {
    public static void main(String[] args) throws Exception {
        ApacheFileMonitor m = new ApacheFileMonitor(5000);
        m.monitor("D:\\temp", new ApacheFileListener());
        m.start();
    }

    private final FileAlterationMonitor monitor;
    public ApacheFileMonitor(long interval) {
        monitor = new FileAlterationMonitor(interval);
    }

    public void monitor(String path, FileAlterationListener listener) {
        FileAlterationObserver observer = new FileAlterationObserver(new File(path));
        monitor.addObserver(observer);
        observer.addListener(listener);
    }

    public void stop() throws Exception{
        monitor.stop();
    }

    public void start() throws Exception {
        monitor.start();
    }
}
